package com.loongtech.bi.action.biflow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.core.util.Time;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.Map.Entry;

/**
 * 
 * ClassName: ItemFlowNewAction
 * 
 * @Description: TODO 实时物品流水
 * @author liuchen
 * @date 2017-5-16 下午6:06:24
 */
@Controller
@Scope("prototype")
@RequestMapping("/flow/itemFlow")
public class ItemFlowNewAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	HadoopQueryManager hadoopQueryManager;

	private Map<String, String> typeItmes = GameParamConfigManager.getItems(CommonGameParam.ITEM_TYPE); // 物品类型



	@RequestMapping(value = "updateServer.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateServer(HttpServletRequest request, HttpServletResponse response, String serverid, String callback) {
		try {
			queryServer = serverid;
			selectServerItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updateChannel.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateChannel(HttpServletRequest request, HttpServletResponse response, String channelid,
			String callback) {
		try {
			queryChannel = channelid;
			selectChannelItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updatePlatform.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updatePlatform(HttpServletRequest request, HttpServletResponse response, String platformid,
			String callback) {
		try {
			queryPlatform = platformid;
			selectPlatformItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	/**
	 * 
	 * @Description: TODO 获取参数
	 * @param @param request
	 * @param @param response
	 * @param @param callback
	 * @return void
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			result.put("reasonItmes", GameParamConfigManager.getItems(CommonGameParam.ITEM_GET_REASON));
			result.put("reasonConsumeItmes", GameParamConfigManager.getItems(CommonGameParam.ITEM_CONSUME_REASON));
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String params,
			String callback) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> m = jsonToMap(params);
			Date dateStart = Time.formatDate((String) m.get("dateStart"), "yyyy-MM-dd");
			Date dateEnd = Time.formatDate((String) m.get("dateEnd"), "yyyy-MM-dd");

			String userid = (String) m.get("userid");
			String roleid = (String) m.get("roleid");
			String itemid = (String) m.get("itemid");

			String platform = (String) m.get("platform");
			String channel = (String) m.get("channel");
			String serverid = (String) m.get("serverid");

			Integer reason = Integer.valueOf((String) m.get("reason"));
			Integer consumeReason = Integer.valueOf((String) m.get("consumeReason"));

			// 开始结束时间不能大于当前时间60天
			if (Time.getInterval(new Date(), dateStart) > 60 || Time.getInterval(new Date(), dateEnd) > 60) {
				result.put("res", "1");
				result.put("msg", "开始结束时间不能小于当前时间60天!");
				printToJson(response, result, callback);
				return;
			}

			// 外部订单号，内部订单号，用户ID，角色ID必要有一个非空
			if (StringUtils.isBlank(userid) && StringUtils.isBlank(roleid) && StringUtils.isBlank(itemid)) {
				result.put("res", "1");
				result.put("msg", "角色ID，帐号ID，物品ID/名称必须至少有一个非空!");
				printToJson(response, result, callback);
				return;
			}
			if (HadoopQueryManager.VISIT_QUEUE.offer("ItemFlowNewAction")) {
				System.out.println("VISIT_QUEUE offer ItemFlowNewAction ok!");

				StringBuffer sql = new StringBuffer();
				sql.append("select logtime,platform,channel,serverid,itemid,userid,roleid,rolelevel,reason, reason as reasonparam ,changenum,leftnum from item where 1=1 ");
				if (userid != null && !"".equals(userid)) {
					sql.append(" and userid = '");
					sql.append(userid.trim());
					sql.append("' ");
				}
				if (!StringUtils.isBlank(roleid)) {
					sql.append(" and cast(roleid as string) = '");
					sql.append(roleid);
					sql.append("' ");
				}
				if (!"0".equals(platform)) {
					sql.append(" and platform = ");
					sql.append(platform);
				}
				if (!"0".equals(channel)) {
					sql.append(" and channel = '");
					sql.append(channel);
					sql.append("' ");
				}
				if (!"0".equals(serverid)) {
					sql.append(" and serverid = ");
					sql.append(serverid);
				}
				if (itemid != null && !"".equals(itemid)) {
					if (typeItmes.get(itemid) != null) { // 名称
						sql.append(" and itemid = '");
						sql.append(typeItmes.get(itemid.trim()));
						sql.append("' ");
					} else {
						sql.append(" and itemid = '");
						sql.append(itemid.trim());
						sql.append("' ");
					}
				}
				if (reason != -99999) {
					sql.append(" and reason = ");
					sql.append(reason);
				}
				if (consumeReason != -99999) {
					sql.append(" and reason = ");
					sql.append(consumeReason);
				}
				sql.append(" and dt >= '");
				sql.append(Time.getDateStr(dateStart));
				sql.append("' and dt <= '");
				sql.append(Time.getDateStr(dateEnd));
				sql.append("' ");
				sql.append(" order by logtime desc ");

				System.out.println(sql.toString());
				Entry<List<String>, List<Object[]>> ret = hadoopQueryManager.executeSQL(sql.toString());
				if (null == ret || null == ret.getKey() || ret.getKey().isEmpty() || null == ret.getValue()) {
                    result.put("res", new ArrayList<Object[]>());
                    result.put("data", "");
                    printToJson(response, result, callback);
					return;
				}
				List<Object[]> lo = ret.getValue();

				for (Object[] o : lo) {
					o[1] = BiPlatformManager.getPlatformNameById((String) o[1]);
					o[2] = BiPlatformManager.getChannelNameById((String) o[2]);
					o[3] = BiPlatformManager.getServerNameById((String) o[3]);
					o[4] = getItemType(o[4]) + "(" + o[4] + ")";
					o[8] = getReasonType(o[8], o[10]) + "(" + o[8] + ")";
					o[9] = ""; //getReasonDetailType(o[9], o[10]) + "(" + o[9] + ")";  // TODO
				}

				result.put("res", "0");
				result.put("data", lo);
				printToJson(response, result, callback);
			} else {
				System.out.println("VISIT_QUEUE offer ItemFlowNewAction failed!");
				result.put("res", "1");
				result.put("msg", "当前系统正被访问，为保证服务器稳定，请稍后再试!");
				printToJson(response, result, callback);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	private Map<String, String> typeItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.ITEM_TYPE); // 物品类型反转

	private Map<String, String> reasonItmesRevise = GameParamConfigManager
			.getItemsRevise(CommonGameParam.ITEM_GET_REASON); // 获得原因反转

	private Map<String, String> reasonDetailItmesRevise = GameParamConfigManager
			.getItemsRevise(CommonGameParam.ITEM_GET_DETAIL_REASON); // 获得原因细分反转

	private Map<String, String> reasonConsumeItmesRevise = GameParamConfigManager
			.getItemsRevise(CommonGameParam.ITEM_CONSUME_REASON); // 消耗原因反转

	private Map<String, String> reasonConsumeDetailItmesRevise = GameParamConfigManager
			.getItemsRevise(CommonGameParam.ITEM_CONSUME_DETAIL_REASON); // 消耗原因细分反转

	// 查询物品名称
	public String getItemType(Object itemType) {
		String key = itemType == null ? "" : Math.abs(Integer.parseInt(itemType.toString())) + "";
		return (typeItmesRevise.get(key) == null) ? key : typeItmesRevise.get(key);
	}

	// 查询消耗/获得类型
	public String getReasonType(Object reasonType, Object num) {
		String key = reasonType == null ? "" : Math.abs(Integer.parseInt(reasonType.toString())) + "";
		int count = num == null ? -9999999 : Integer.parseInt(num.toString());
		return count > 0 ? ((reasonItmesRevise.get(key) == null) ? key : reasonItmesRevise.get(key))
				: ((reasonConsumeItmesRevise.get(key) == null) ? key : reasonConsumeItmesRevise.get(key));
	}

	// 查询消耗/获得细分类型
	public String getReasonDetailType(Object reasonDeailType, Object num) {
		String key = reasonDeailType == null ? "" : Math.abs(Integer.parseInt(reasonDeailType.toString())) + "";
		int count = num == null ? -9999999 : Integer.parseInt(num.toString());
		return count > 0 ? ((reasonDetailItmesRevise.get(key) == null) ? key : reasonDetailItmesRevise.get(key))
				: ((reasonConsumeDetailItmesRevise.get(key) == null) ? key : reasonConsumeDetailItmesRevise.get(key));
	}

	@Override
	public void search() {
		// TODO Auto-generated method stub

	}

	@Override
	protected String csvContent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String csvFileName() {
		// TODO Auto-generated method stub
		return null;
	}
}
